﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Globalization;
using System.IO;
using System.Text;

using CE.User;
using CE.Mail;
using CE.Global;
using CE.Security;

public partial class user_edit_profile : MyLanguageBasePage
{
    string _redirectUrl = "";
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.Title.EditProfileTitle;

        LiteralControl newln = new LiteralControl(Environment.NewLine);
        HtmlMeta language = new HtmlMeta();
        language.Name = "language";
        language.Content = Resources.Title.PageLanguage;

        HtmlMeta keywords = new HtmlMeta();
        keywords.Name = "keywords";
        keywords.Content = Resources.Title.EditProfileKeyword;

        HtmlMeta description = new HtmlMeta();
        description.Name = "description";
        description.Content = Resources.Title.EditProfileDescription;

        Page.Header.Controls.AddAt(10, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(11, language);
        Page.Header.Controls.AddAt(12, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(13, keywords);
        Page.Header.Controls.AddAt(14, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(15, description);


        if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.UserTypeId] != null)
        {
            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Customer) && Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Provider))
            {
                _redirectUrl = CE.Global.General.GetUrl("/", Page);
                Response.Redirect(_redirectUrl);
            }
        }
        else
        {
            _redirectUrl = CE.Global.General.GetUrl("/", Page);
            Response.Redirect(_redirectUrl);
        }


        if (!Page.IsPostBack)
        {
            //btnSubmit.OnClientClick = "javascript:return confirm('" + Resources.General.Confirm + "');";

            LoadDOB();
            LoadOccupation();
            ShowUserDetails();

            txtEmail.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtEmail.ClientID + "','" + rfvEmail.ClientID + "','" + revEmail.ClientID + "');");
            txtName.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtName.ClientID + "','" + rfvName.ClientID + "','" + revName.ClientID + "');");
            txtMobile.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtMobile.ClientID + "','" + rfvMobile.ClientID + "','" + revMobile.ClientID + "');");
            ddlDay.Attributes.Add("onblur", "ShowValidationEffect('" + ddlDay.ClientID + "','" + rfvDay.ClientID + "');");
            ddlMonth.Attributes.Add("onblur", "ShowValidationEffect('" + ddlMonth.ClientID + "','" + rfvMonth.ClientID + "');");
            ddlYear.Attributes.Add("onblur", "ShowValidationEffect('" + ddlYear.ClientID + "','" + rfvYear.ClientID + "');");
            ddlOccupation.Attributes.Add("onblur", "ShowValidationEffect('" + ddlOccupation.ClientID + "','" + rfvOccupation.ClientID + "');");
        }
        LogUserViewedHistory();
        Page.Form.DefaultButton = btnSubmit.UniqueID;
    }

    private void LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        _userviewdb.LogViewedHistory("USR", Request, "User edit profile.");
    }

    private void ShowUserDetails()
    {
        CE.User.Profile _profile = new CE.User.Profile();
        CE.User.ProfileDB _profiledb = new ProfileDB();
        CE.User.Contact _contact = new Contact();
        CE.User.ContactDB _contactdb = new ContactDB();
        Int64 UserId = Convert.ToInt64(Session[General.UserId].ToString());
        _profile = _profiledb.GetProfile(UserId);
        if (_profile != null)
        {
            txtName.Text = _profile.FirstName + (_profile.SurName.Trim() != "" ? " " + _profile.SurName.Trim() : "");
            ddlDay.Text = _profile.DOB.Day.ToString();
            ddlMonth.Text = _profile.DOB.Month.ToString();
            ddlYear.Text = _profile.DOB.Year.ToString();

            ddlGender.Text = _profile.Gender.ToString();

            if (_profile.Occupation != -1)
                ddlOccupation.Text = _profile.Occupation.ToString();

            _contact = _contactdb.GetContact(UserId);
            if (_contact != null)
            {
                txtEmail.Text = _contact.Email;
                txtMobile.Text = _contact.Mobile;
            }
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        ChangeValidationEffectServerSide("profile");
        Page.Validate("profile");
        if (Page.IsValid)
        {
            int _day = Convert.ToInt32(ddlDay.Text);
            int _month = Convert.ToInt32(ddlMonth.Text);
            int _year = Convert.ToInt32(ddlYear.Text);
            if (!ValidDate(_year, _month, _day))
            {
                lblErrorMessage.ForeColor = System.Drawing.Color.Red;
                lblErrorMessage.Text = Resources.UserMessage.SelectValidDOB;// "Please select valid DOB";
                return;
            }
            DateTime _dtDOB = new DateTime(_year, _month, _day);

            //AccountDB _accountdb = new AccountDB();
            //Account _account = _accountdb.CheckEmail(Session[CE.Global.General.UserEmail].ToString(), Convert.ToInt32(CE.Global.CEUserType.Customer));
            //if (_account != null)
            //{
            //    string _Password = txtPassword.Text;
            //    if (_account.AuthCode != _Password)
            //    {
            //        lblErrorMessage.ForeColor = System.Drawing.Color.Red;
            //        lblErrorMessage.Text = Resources.UserMessage.EnterCorrectPassowrd;
            //        return;
            //    }
            //}

            txtName.Text = CE.Global.General.ClearScriptTag(txtName.Text);
            Int64 _userId = Convert.ToInt64(Session[General.UserId].ToString());
            Profile _userprofile = null;
            ProfileDB _userprofiledb = new ProfileDB();
            Contact _contact = null;
            ContactDB _contactdb = new ContactDB();

            if (_userId > 0)
            {
                _userprofile = _userprofiledb.GetProfile(_userId);
                if (_userprofile == null)
                {
                    _userprofile = new Profile();
                }
                _userprofile.FirstName = Server.HtmlEncode(txtName.Text);
                //_userprofile.SurName = Server.HtmlEncode(txtName.Text);
                _userprofile.DOB = _dtDOB;
                _userprofile.Gender = Convert.ToChar(ddlGender.Text);
                _userprofile.Occupation = Convert.ToInt32(ddlOccupation.Text);
                _userprofile.IDType = "";
                _userprofile.RefCEUserId = _userId;
                _userprofile.Status = "Complete";

                Int64 _profileresult = _userprofiledb.Insert(_userprofile);

                _contact = _contactdb.GetContact(_userId);
                if (_contact == null)
                {
                    _contact = new Contact();
                }

                _contact.Mobile = Server.HtmlEncode(txtMobile.Text.Trim());
                _contact.Email = Server.HtmlEncode(txtEmail.Text.Trim());
                _contact.Status = true;
                _contact.RefCEUserId = _userId;
                if (Session[General.AgentId] != null)
                {
                    _contact.Info2 = Session[General.AgentId].ToString();
                    _contact.Info3 = DateTime.Now.ToString();
                }

                Int64 _contactresult = _contactdb.Insert(_contact);

                if (_profileresult > 0 && _contactresult > 0)
                {
                    Session[General.UserName] = txtName.Text;

                    Session[General.UserPhoneNo] = txtMobile.Text.Trim();
                    if (_userprofile.YearDriveSg > 0)
                    {
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    }

                    SetCookies();
                    lblErrorMessage.ForeColor = System.Drawing.Color.Green;
                    lblErrorMessage.Text = Resources.General.ChangeUpdated; //"Successfully Updated";
                    string _urlPath = "~/";
                    try
                    {
                        if (Page.Request.Params["redir"] != null)
                        {
                            string _tempUrlPath = GetRedirectUrl(Page.Request.Params["redir"].ToString());
                            string testUrl = Server.MapPath(_tempUrlPath);
                            _urlPath = Server.UrlDecode(_tempUrlPath);
                        }
                        _redirectUrl = CE.Global.General.GetUrl("/user/user-message", Page);
                        Session["UMMSG"] = "UMG,1995";
                        Response.Redirect(_redirectUrl);
                    }
                    catch (Exception Ex)
                    {
                        Ex = null;
                        _urlPath = "~/";
                    }
                    finally
                    {
                        //lblSetInsMessage.Text = Resources.General.ChangeUpdated;
                        _redirectUrl = CE.Global.General.GetUrl(_urlPath, Page);
                    }
                }
            }
        }
    }

    private string GetRedirectUrl(string strPathId)
    {
        string retValue = "";
        retValue = "~/";
        return retValue;
    }

    public bool ValidDate(Int32 Year, Int32 Month, Int32 Day)
    {
        bool _isValid = true;
        int daysInMonth = 0;
        string leap, monthValid, dayValid, yearValid;
        if (Year >= 0000)
        {
            yearValid = "yes";
        }
        else
        {
            yearValid = "no";
        }
        if (Year % 400 == 0)
        {
            leap = "yes";
        }
        else if (Year % 100 == 0)
        {
            leap = "no";
        }
        else if (Year % 4 == 0)
        {
            leap = "yes";
        }
        else
        {
            leap = "no";
        }

        switch (Month)
        {
            case 1: daysInMonth = 31;
                break;
            case 3: daysInMonth = 31;
                break;
            case 4: daysInMonth = 30;
                break;
            case 5: daysInMonth = 31;
                break;
            case 6: daysInMonth = 30;
                break;
            case 7: daysInMonth = 31;
                break;
            case 8: daysInMonth = 31;
                break;
            case 9: daysInMonth = 30;
                break;
            case 10: daysInMonth = 31;
                break;
            case 11: daysInMonth = 30;
                break;
            case 12: daysInMonth = 31;
                break;
        }

        if (Month >= 1 && Month <= 12)
        {
            monthValid = "yes";
        }
        else
        {
            monthValid = "no";
        }
        if (Month == 2)
        {
            if (leap == "no")
            {
                daysInMonth = 28;
            }
            else if (leap == "yes")
            {
                daysInMonth = 29;
            }
        }

        if (1 <= Day && Day <= daysInMonth)
        {
            dayValid = "yes";
        }

        else
        {
            dayValid = "no";
        }

        if ((dayValid == "yes") && (monthValid == "yes") && (yearValid == "yes"))
        {
            _isValid = true;
        }
        else
        {
            _isValid = false;
        }

        return _isValid;
    }

    private void LoadDOB()
    {
        ddlDay.Items.Clear();
        for (int _day = 1; _day <= 31; _day++)
        {
            ddlDay.Items.Add(new ListItem(_day.ToString("00"), _day.ToString("00")));
        }
        ddlDay.Items.Insert(0, new ListItem(Resources.General.Day, "-1"));

        ddlYear.Items.Clear();
        int _styr = CE.Global.General.GetUTCDateTime().Year - 18;
        int _endyr = _styr - 70;
        for (int _year = _styr; _year >= _endyr; _year--)
        {
            ddlYear.Items.Add(new ListItem(_year.ToString(), _year.ToString()));
        }
        ddlYear.Items.Insert(0, new ListItem(Resources.General.Year, "-1"));
    }

    private void LoadOccupation()
    {
        DataTable dtOccupation = General.GetComboItem(Resources.General.OccupationList, Resources.General.OccupationSortBy, true);
        ddlOccupation.DataSource = dtOccupation;
        ddlOccupation.DataTextField = dtOccupation.Columns[0].ColumnName.ToString();
        ddlOccupation.DataValueField = dtOccupation.Columns[1].ColumnName.ToString();
        ddlOccupation.DataBind();
        ddlOccupation.Items.Insert(0, new ListItem(Resources.General.Select, "-1"));
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        txtName.Text = HttpUtility.HtmlEncode(txtName.Text);
        txtEmail.Text = HttpUtility.HtmlEncode(txtEmail.Text);
        txtMobile.Text = HttpUtility.HtmlEncode(txtMobile.Text);

        //Name
        if (rfvName.Enabled && rfvName.ValidationGroup == strValidationGroup)
        {
            rfvName.Validate();
            if (rfvName.IsValid == false)
            {
                txtName.ControlStyle.CssClass = "pw-fields validationError";
            }
            else
            {
                txtName.ControlStyle.CssClass = "pw-fields";
            }
        }
        else
        {
            txtName.ControlStyle.CssClass = "pw-fields";
        }

        if (revName.Enabled && revName.ValidationGroup == strValidationGroup)
        {
            if (rfvName.IsValid)
            {
                revName.Validate();
                if (revName.IsValid == false)
                {
                    txtName.ControlStyle.CssClass = "pw-fields validationError";
                }
                else
                {
                    txtName.ControlStyle.CssClass = "pw-fields";
                }
            }
        }
        else
        {
            txtName.ControlStyle.CssClass = "pw-fields";
        }

        //Email
        if (rfvEmail.Enabled && rfvEmail.ValidationGroup == strValidationGroup)
        {
            rfvEmail.Validate();
            if (rfvEmail.IsValid == false)
            {
                txtEmail.ControlStyle.CssClass = "pw-fields validationError";
            }
            else
            {
                txtEmail.ControlStyle.CssClass = "pw-fields";
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "pw-fields";
        }

        if (revEmail.Enabled && revEmail.ValidationGroup == strValidationGroup)
        {
            if (rfvEmail.IsValid)
            {
                revEmail.Validate();
                if (revEmail.IsValid == false)
                {
                    txtEmail.ControlStyle.CssClass = "pw-fields validationError";
                }
                else
                {
                    txtEmail.ControlStyle.CssClass = "pw-fields";
                }
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "pw-fields";
        }

        //MobileNo
        if (rfvMobile.Enabled && rfvMobile.ValidationGroup == strValidationGroup)
        {
            rfvMobile.Validate();
            if (rfvMobile.IsValid == false)
            {
                txtMobile.ControlStyle.CssClass = "pw-fields validationError";
            }
            else
            {
                txtMobile.ControlStyle.CssClass = "pw-fields";
            }
        }
        else
        {
            txtMobile.ControlStyle.CssClass = "pw-fields";
        }

        if (revMobile.Enabled && revMobile.ValidationGroup == strValidationGroup)
        {
            if (rfvMobile.IsValid)
            {
                revMobile.Validate();
                if (revMobile.IsValid == false)
                {
                    txtMobile.ControlStyle.CssClass = "pw-fields validationError";
                }
                else
                {
                    txtMobile.ControlStyle.CssClass = "pw-fields";
                }
            }
        }
        else
        {
            txtMobile.ControlStyle.CssClass = "pw-fields";
        }

        //day
        if (rfvDay.Enabled && rfvDay.ValidationGroup == strValidationGroup)
        {
            rfvDay.Validate();
            if (rfvDay.IsValid == false)
            {
                ddlDay.ControlStyle.CssClass = "pw-row-2 validationError";
            }
            else
            {
                ddlDay.ControlStyle.CssClass = "pw-row-2";
            }
        }
        else
        {
            ddlDay.ControlStyle.CssClass = "pw-row-2";
        }

        //Month
        if (rfvMonth.Enabled && rfvMonth.ValidationGroup == strValidationGroup)
        {
            rfvMonth.Validate();
            if (rfvMonth.IsValid == false)
            {
                ddlMonth.ControlStyle.CssClass = "pw-row-2 validationError";
            }
            else
            {
                ddlMonth.ControlStyle.CssClass = "pw-row-3";
            }
        }
        else
        {
            ddlMonth.ControlStyle.CssClass = "pw-row-3";
        }

        //Year
        if (rfvYear.Enabled && rfvYear.ValidationGroup == strValidationGroup)
        {
            rfvYear.Validate();
            if (rfvYear.IsValid == false)
            {
                ddlYear.ControlStyle.CssClass = "pw-row-4 validationError";
            }
            else
            {
                ddlYear.ControlStyle.CssClass = "pw-row-4";
            }
        }
        else
        {
            ddlYear.ControlStyle.CssClass = "pw-row-4";
        }

        //Occupation
        if (rfvOccupation.Enabled && rfvOccupation.ValidationGroup == strValidationGroup)
        {
            rfvOccupation.Validate();
            if (rfvOccupation.IsValid == false)
            {
                ddlOccupation.ControlStyle.CssClass = "pw-row-6 validationError";
            }
            else
            {
                ddlOccupation.ControlStyle.CssClass = "pw-row-6";
            }
        }
        else
        {
            ddlOccupation.ControlStyle.CssClass = "pw-row-6";
        }

        //Occupation
        //if (rfvPassword.Enabled && rfvPassword.ValidationGroup == strValidationGroup)
        //{
        //    rfvPassword.Validate();
        //    if (rfvPassword.IsValid == false)
        //    {
        //        txtPassword.ControlStyle.CssClass = "pw-fields validationError";
        //    }
        //    else
        //    {
        //        txtPassword.ControlStyle.CssClass = "pw-fields";
        //    }
        //}
        //else
        //{
        //    txtPassword.ControlStyle.CssClass = "pw-fields";
        //}

    }

    private void SetCookies()
    {
        try
        {
            HttpCookie _cookie = new HttpCookie("GGQuote");
            _cookie.Values.Add("CustomerName", MySecurity.Encrypt(Session[CE.Global.General.UserName].ToString(), true));
            _cookie.Values.Add("CustomerEmail", MySecurity.Encrypt(Session[CE.Global.General.UserEmail].ToString(), true));
            _cookie.Values.Add("CustomerMobile", MySecurity.Encrypt(Session[CE.Global.General.UserPhoneNo].ToString(), true));

            _cookie.Expires = DateTime.Now.AddDays(60);
            Response.Cookies.Add(_cookie);
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

}
